<?php
/**
 * Created by PhpStorm.
 * User: chenzhenlin
 * Date: 2019/2/14
 * Time: 2:21 PM
 */

namespace app\common\utils;


class Functions
{

    /**
     * 把网络图片图片转成base64
     * @param string $img
     * @return string
     */
    public static function imgToBase64($img = '')
    {
        if (empty($img)) return '';
        $imageInfo = getimagesize($img);
        return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));
    }

    /**
     * 格式化列表
     * @param $list
     * @param $page
     * @param $per_page
     * @param $total
     * @param bool $isAddIndex false  是否添加序号
     * @param $totalRow
     * @return array
     */
    public static function formatList($list, $page, $per_page, $total, $isAddIndex = false, $totalRow = [])
    {
        if (!empty($list)) {
            foreach ($list as $key => &$value) {
                if ($isAddIndex && !isset($value['index'])) $value['index'] = ($page - 1) * $per_page + $key + 1;
            }
        }

        $result = [

            'list' => $list,
            'page' => $page,
            'last_page' => $per_page > 0 ? ceil($total / $per_page) : 1,
            'per_page' => $per_page,
            'total' => $total,

        ];
        if($totalRow) $result['totalRow'] = $totalRow;
        return $result;
    }


    /**
     * 价格格式化
     * @param $price
     * @param $decimals 小数点位数
     * @return string 返回字符串格式
     */
    public static function formatPrice($price, $decimals = 2)
    {
        $price_format = number_format($price, $decimals, '.', '');
        return $price_format;
    }

    /**
     * 格式化日期输出
     * @param $time
     * @return false|string
     */
    public static function formatDate($time)
    {
        if (empty($time)) return '';
        if (is_numeric($time)) return date('Y-m-d', $time);
        return date('Y-m-d', strtotime($time));
    }

    /**
     * 格式化日期输出(含时间)
     * @param $time
     * @return false|string
     */
    public static function formatDateTime($time,$format = null)
    {
        if (empty($time)) return '';
        if (is_numeric($time)) return date($format ? $format : 'Y-m-d H:i:s' , $time);
        return date($format ? $format : 'Y-m-d H:i:s' , strtotime($time));
    }


    /**
     * 千分位
     * @author: zhoujian 2020/6/4/004
     * @param $money
     * @param int $decimals
     * @return float
     */
    public static function thousands($money, $decimals = 2)
    {
        if (!is_numeric($money)) return $money;
        $money = number_format($money, $decimals, '.', ',');
        return $money;
    }

    /**
     * 删除数组
     * @param $arr
     * @param $count
     */
    public static function popArray(&$arr, $count = 1)
    {
        for ($i = 0; $i < $count; $i++) {
            array_pop($arr);
        }
    }


    /**
     * 截取字符串
     * @param $string 字符串
     * @param $length 长度
     * @param string $encode = utf-8 编码
     * @param string $beyondChar = ... 超出部分 代替符号
     * @return string
     */
    public static function subString($string, $length, $encode = 'utf-8', $beyondChar = '...')
    {
        return mb_substr($string, 0, $length, $encode) . (mb_strlen($string) > $length ? $beyondChar : '');
    }




    /**
     * 获取以 $keyName字段 的值下标对应的 数组
     * array(
     *   key1 => array( key1 => value1)
     * )
     * @param $list
     * @param $keyName
     */
    public static function getKeyValueList($list, $keyName)
    {
        return array_combine(array_column($list, $keyName), $list);
    }


    /**
     *  设置 选择选项
     * @param $option
     * @param string $keyName 键名
     * @param string $keyName 值键名
     *
     * @return array
     * 格式1
     * array(
     *   key1 => value1,
     *   key1 => value1,
     *   key1 => value1,
     * )
     */
    public static function setSelectOption($option, $keyName = '', $valueName = '')
    {
        if (!empty($keyName) && !empty($valueName)) {
            $option = array_combine(array_column($option, $keyName), array_column($option, $valueName));
        }
        return ['' => '请选择'] + $option;//保持键值
    }

    /**
     * 验证手机
     * Created by PhpStorm.
     * User: D.Li
     * Date: 2019/11/20
     * Time: 16:19
     * @param $mobile
     * @return bool
     */
    public static function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^1[1,2,3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
    }


    /**
     * 验证邮箱
     * Created by PhpStorm.
     * User: D.Li
     * Date: 2019/11/20
     * Time: 16:26
     * @param $str
     * @return bool
     */
    public static function isEmail($str)
    {
        if (!$str) {
            return false;
        }
        return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $str) ? true : false;
    }

    /**
     * 获取客户端手机型号
     * @param $agent //$_SERVER['HTTP_USER_AGENT']
     * @return array[mobile_brand]      手机品牌
     * @return array[mobile_ver]        手机型号
     * @return array[is_mobile]         是否是手机端
     */
    public static function getClientMobileBrand($agent = '')
    {
        if (empty($agent)) $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $is_mobile = 1;
        if (stripos($agent, 'android') === false || stripos($agent, 'iPhone') === false || stripos($agent, 'BlackBerry') === false) {
            $is_mobile = 0;
        }

        if (preg_match('/iPhone\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '苹果';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/SAMSUNG|Galaxy|GT-|SCH-|SM-\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '三星';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Huawei|Honor|H60-|H30-\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '华为';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Mi note|mi one\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '小米';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/HM NOTE|HM201\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '红米';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Coolpad|8190Q|5910\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '酷派';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/ZTE|X9180|N9180|U9180\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '中兴';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/OPPO|X9007|X907|X909|R831S|R827T|R821T|R811|R2017\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = 'OPPO';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/HTC|Desire\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = 'HTC';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Nubia|NX50|NX40\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '努比亚';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/M045|M032|M355\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '魅族';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Gionee|GN\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '金立';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/HS-U|HS-E\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '海信';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Lenove\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '联想';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/ONEPLUS\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '一加';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/vivo\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = 'vivo';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/K-Touch\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '天语';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/DOOV\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '朵唯';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/GFIVE\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '基伍';
            $mobile_ver = $regs[0];
        } elseif (preg_match('/Nokia\s([^\s|;]+)/i', $agent, $regs)) {
            $mobile_brand = '诺基亚';
            $mobile_ver = $regs[0];
        } else {
            $mobile_brand = '其他';
            $mobile_ver = '未知';
            $is_mobile = 0;
        }
        return ['mobile_brand' => $mobile_brand, 'mobile_ver' => $mobile_ver, 'is_mobile' => $is_mobile];
    }

    /**
     * 获取客户端浏览器以及版本号
     * @param $agent //$_SERVER['HTTP_USER_AGENT']
     * @return array[browser]       浏览器名称
     * @return array[browser_ver]   浏览器版本号
     */
    public static function getClientBrowser($agent = '')
    {
        if (empty($agent)) $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $browser = '';
        $browser_ver = '';
        if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'OmniWeb';
            $browser_ver = $regs[2];
        }
        if (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Netscape';
            $browser_ver = $regs[2];
        }
        if (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Safari';
            $browser_ver = $regs[1];
        }
        if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'Internet Explorer';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
            $browser = 'Opera';
            $browser_ver = $regs[1];
        }
        if (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') NetCaptor';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Maxthon/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') Maxthon';
            $browser_ver = '';
        }
        if (preg_match('/360SE/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') 360SE';
            $browser_ver = '';
        }
        if (preg_match('/SE 2.x/i', $agent, $regs)) {
            $browser = '(Internet Explorer ' . $browser_ver . ') 搜狗';
            $browser_ver = '';
        }
        if (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'FireFox';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Lynx';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Chrome';
            $browser_ver = $regs[1];
        }
        if (preg_match('/MicroMessenger\/([^\s]+)/i', $agent, $regs)) {
            $browser = '微信浏览器';
            $browser_ver = $regs[1];
        }
        if ($browser != '') {
            return ['browser' => $browser, 'browser_ver' => $browser_ver];
        } else {
            return ['browser' => '未知', 'browser_ver' => ''];
        }
    }

    /**
     * 获取客户端操作系统
     * @param $agent //$_SERVER['HTTP_USER_AGENT']
     * @return array[os]            操作系统名称
     * @return array[os_ver]        操作系统版本号
     * @return array[equipment]     终端设备类型
     */
    public static function getClientOS($agent = '')
    {
        if (empty($agent)) $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $os = '';
        $os_ver = '';
        $equipment = '';
        //window系统
        if (stripos($agent, 'window')) {
            $os = 'Windows';
            $equipment = '电脑';
            if (preg_match('/nt 6.0/i', $agent)) {
                $os_ver = 'Vista';
            } elseif (preg_match('/nt 10.0/i', $agent)) {
                $os_ver = '10';
            } elseif (preg_match('/nt 6.3/i', $agent)) {
                $os_ver = '8.1';
            } elseif (preg_match('/nt 6.2/i', $agent)) {
                $os_ver = '8.0';
            } elseif (preg_match('/nt 6.1/i', $agent)) {
                $os_ver = '7';
            } elseif (preg_match('/nt 5.1/i', $agent)) {
                $os_ver = 'XP';
            } elseif (preg_match('/nt 5/i', $agent)) {
                $os_ver = '2000';
            } elseif (preg_match('/nt 98/i', $agent)) {
                $os_ver = '98';
            } elseif (preg_match('/nt/i', $agent)) {
                $os_ver = 'nt';
            } else {
                $os_ver = '';
            }
            if (preg_match('/x64/i', $agent)) {
                $os .= '(x64)';
            } elseif (preg_match('/x32/i', $agent)) {
                $os .= '(x32)';
            }
        } elseif (stripos($agent, 'linux')) {
            if (stripos($agent, 'android')) {
                preg_match('/android\s([\d\.]+)/i', $agent, $match);
                $os = 'Android';
                $equipment = 'Mobile phone';
                $os_ver = $match[1];
            } else {
                $os = 'Linux';
            }
        } elseif (stripos($agent, 'unix')) {
            $os = 'Unix';
        } elseif (preg_match('/iPhone|iPad|iPod/i', $agent)) {
            preg_match('/OS\s([0-9_\.]+)/i', $agent, $match);
            $os = 'IOS';
            $os_ver = str_replace('_', '.', $match[1]);
            if (preg_match('/iPhone/i', $agent)) {
                $equipment = 'iPhone';
            } elseif (preg_match('/iPad/i', $agent)) {
                $equipment = 'iPad';
            } elseif (preg_match('/iPod/i', $agent)) {
                $equipment = 'iPod';
            }
        } elseif (stripos($agent, 'mac os')) {
            preg_match('/Mac OS X\s([0-9_\.]+)/i', $agent, $match);
            $os = 'Mac OS X';
            $equipment = '电脑';
            $os_ver = str_replace('_', '.', $match[1]);
        } else {
            $os = 'Other';
        }
        return ['os' => $os, 'os_ver' => $os_ver, 'equipment' => $equipment];
    }


    /**
     * @remarks:获取当月第一天及最后一天
     * @author: lzj 2020/5/19
     * @param $date
     * @return array
     */
    public static function getMonth($date)
    {
        $firstDay = date('Y-m-01', strtotime($date));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        return ['firstDay' => $firstDay, 'lastDay' => $lastDay];
    }

    /**
     * @remarks: 获取本周第一天及最后一天（周一为第一天）
     * @author: lzj 2020/5/19
     * @return array
     */
    public static function getWeek()
    {
        $firstDay = date('Y-m-d', strtotime('this week'));
        $lastDay = date('Y-m-d', strtotime('last day next week'));
        return ['firstDay' => $firstDay, 'lastDay' => $lastDay];
    }

    /**
     * @description 获取近三个月的开始时间和结束时间
     * @author dyl
     */
    public static function threeMonth(){
        $now = time();
        $time = strtotime('-2 month', $now);
        $beginTime = date('Y-m-d 00:00:00', mktime(0, 0,0, date('m', $time), 1, date('Y', $time)));
        $endTime = date('Y-m-d 23:39:59', mktime(0, 0, 0, date('m', $now), date('t', $now), date('Y', $now)));

        return [$beginTime, $endTime];
    }

    /**
     * @description 获取本年的开始时间和结束时间
     * @author dyl
     */
    public static function thisYear(){
        $now = time();
        $beginTime = date('Y-m-d 00:00:00', mktime(0, 0, 0, 1, 1, date('Y', $now)));
        $endTime = date('Y-m-d 23:39:59', mktime(0, 0, 0, 12, 31, date('Y', $now)));

        return [$beginTime, $endTime];
    }

    /**
     * @description 获取本月(当月)的开始时间和结束时间
     * @author dyl
     */
    public static function thisMonth(){
        $now = time();
        $beginTime = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m', $now), '1', date('Y', $now)));
        $endTime = date('Y-m-d 23:39:59', mktime(0, 0, 0, date('m', $now), date('t', $now), date('Y', $now)));

        return [$beginTime, $endTime];
    }

}